import React from 'react'
import { connect } from 'dva'
import { hashHistory } from 'dva/router'
import { Form, Button, Icon, Dropdown, Menu, Modal } from 'antd'
import ListPage from 'widget/PageTmpl/ListPage'
import { mapStateToProps } from 'utils/view_utils'
const mockData = {
    "resultCode": "0",
    "resultMsg": "查询成功",
    "data": {
        "list": [
            {
                "roleName": "系统管理员",
                "description": "管理所有系统",
                "createPerson": "张三",
                "createDate": "2017-12-21 10:09:38",
                "status": "1",
                "statusName": "启用"
            },
            {
                "roleName": "普通会员",
                "description": "网站注册用户",
                "createPerson": "李四",
                "createDate": "2017-12-21 12:39:33",
                "status": "2",
                "statusName": "禁用"
            }
        ],
        "pageNo": 1,
        "pageSize": 10,
        "pages": 1,
        "total": 2,
    }
}
import config from '../../../../config/config'
/*
 * 权限管理-角色新增/角色编辑
 * @author 廖玉宾
 * @time 未知
 * */
const routeView = ({ dispatch, model, form }) => {

	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form;
	const { modelObj, namespace } = model;

	// 获取此时的应用的操作系统
	const { operationSystem = 'sys' } = MODULE_TO_ROUTES[namespace];

	// 表格模板中的表格列配置
	const columns = [
		{ en_name: 'roleName', zh_name: '角色名称' },
		{ en_name: 'description', zh_name: '角色说明',width:440 },
    {en_name: 'status', zh_name: '状态',
			render: data => {
    	return {1: '启用', 2: '禁用'}[data] || ''}
    	},
	];

	// 批量操作下拉菜单
	const menu = (
		<Menu onClick={(e) => { batch(e.key) }}>
			<Menu.Item key="delete">批量删除</Menu.Item>
			<Menu.Item key="forbid">批量禁用</Menu.Item>
			<Menu.Item key="open">批量启用</Menu.Item>
		</Menu>
	);

  // 再次确认提示框
  function againConfirmation(actionType, actionId, message, modalTheme = 'confirm') {
	  // 设置传入的参数
    const params = { id: actionId ? actionId : modelObj.biz.selectedRows.map(item => item.id).join(',') };

    // 当为批量操作状态时，需要额外传入参数 -- 1：批量启用；2：批量禁用
    if (['forbid', 'open'].includes(actionType)) {
      params.status = actionType === 'forbid' ? 2 : 1;
    }

    // 根据当前弹出框的操作类型，设置调用的方法
    const funName = ['singleDelete', 'delete'].includes(actionType) ? 'batchDelete' : 'batchUpdate';

    // 设置提示信息，删除时的提示信息由接口返回
    const tips = message ? message : actionType === 'forbid' ? `确定要禁用选中的角色吗？` : `确定要启用选中的角色吗？`;

    Modal[modalTheme]({
      title: '友情提示',
      content: tips,
      maskClosable: true,
      okText: '确定', cancelText: '取消',
      onOk: () => {
        dispatch({ type: `${namespace}/${funName}`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
      }
    })
  }

	// 角色删除校验
	function selfDelete(type, item) {
		dispatch({
			type: `${namespace}/checkDelete`,
			payload: {
				params: { id: item.id },
        callback: (actionId, message) => againConfirmation(type, actionId, message)
			}
		})
	}

	// 批量操作 - 删除、启用、禁用
	function batch(type) {
    if (type === 'delete') { // 批量删除时，需要由接口返回提示信息
      dispatch({
        type: `${namespace}/checkDelete`,
        payload: {
          params: { id: modelObj.biz.selectedRows.map(item => item.id).join(',') },
          callback: (actionId, message) => againConfirmation(type, actionId, message)
        }
      });
    } else {
      againConfirmation(type);
    }
	}

  // 单个角色状态切换
  function changeStatus(item) {
    let status = 1;
    if (item.status == 1) { status = 2 }
    dispatch({
      type: `${namespace}/changeStatus`,
      payload: {
        params: { id: item.id, status: status },
        cb: () => { fresh() }
      }
    })
  }

  // 表单刷新
	function fresh() {
    // 刷新列表数据
    modelObj.biz.refreshListDatas(true)
  }

  // 表格模板配置
	let pageProps = {
		// ---------- 界面部分 ----------
		ui: {
            // 页面接口地址
            api_url: '',
			method: "GET",
			params: "pageNo=1&pageSize=10",
			mockData: mockData,
			//查询栏
			search_bar: {
				fields: [
					{
						en_name: "roleName",
						zh_name: "角色名称",
						elem_type: "Input",
						elem_valid_type: "string"
					},
					{
						en_name: "status",
						zh_name: "状态",
						elem_type: "Select",
						elem_valid_type: "string",
						cmpt_items: [
							{ "label": "启用", "value": "1" },
							{ "label": "禁用", "value": "2" }
						],
					},
				]
			},
			//右上角操作栏
			"action_bar": [
				{
					func_name: "onAdd",
					label: "新增",
					type: "primary",
					icon: "plus",
					onClick: (e) => {
						hashHistory.push({
							pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
							query: { type: 'add' }
						})
					}
				}
			],
			// 数据表格
			table: {
				fields:  columns,
				action_props: {
					width: 120,
				},
				actions: [
					{
						func_name: "onEdit",
						label: "",
						render: (item) => {
							return <a href='javascript:;' onClick={e => hashHistory.push({
								pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
								query: { type: 'edit', id: item.id }
							})}>编辑</a>
						}
					},
					{
						func_name: "onToggleStatus",
						render: (item) => {
							return <a href='javascript:;' onClick={e => { changeStatus(item) }}>{item.status == 1 ? '禁用' : '启用'}</a>
						}
					},
					{
						func_name: "onSelfDelete",
						render: (item) => {
							return <a href='javascript:;' onClick={e => { selfDelete('singleDelete', item) }}>删除</a>
						}
					},
				],
			}
		}
	};

	if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/setFormVal`,
				payload: biz
			})
		}
	}

	return <ListPage pageProps={pageProps} />

};

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
